<template>
  <view class="payment-record-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">缴费记录</text>
      <text class="nav-export" @click="exportRecords">导出</text>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-card">
        <view class="stats-item">
          <text class="stats-num">{{ stats.totalAmount }}</text>
          <text class="stats-label">总缴费金额</text>
        </view>
        <view class="stats-item">
          <text class="stats-num">{{ stats.totalCount }}</text>
          <text class="stats-label">缴费次数</text>
        </view>
        <view class="stats-item">
          <text class="stats-num">{{ stats.monthAmount }}</text>
          <text class="stats-label">本月缴费</text>
        </view>
      </view>
    </view>

    <!-- 筛选条件 -->
    <view class="filter-section">
      <view class="filter-item" @click="showStatusPicker">
        <text class="filter-label">缴费状态</text>
        <text class="filter-value">{{ statusText }}</text>
        <text class="filter-arrow">></text>
      </view>
    </view>

    <!-- 缴费记录列表 -->
    <view class="record-list">
      <view 
        class="record-item" 
        v-for="item in recordList" 
        :key="item.id"
        @click="viewDetail(item)"
      >
        <view class="item-header">
          <view class="item-info">
            <text class="item-name">{{ item.chName }}</text>
            <text class="item-phone">{{ item.chMobile }}</text>
          </view>
          <view class="item-status" :class="getStatusClass(item.orderStatus)">
            <text class="status-text">{{ getStatusText(item.orderStatus) }}</text>
          </view>
        </view>
        
        <view class="item-body">
          <view class="item-detail">
            <text class="detail-label">订单号：</text>
            <text class="detail-value">{{ item.orderNo }}</text>
          </view>
          <view class="item-detail">
            <text class="detail-label">缴费类型：</text>
            <text class="detail-value">{{ getPaymentType(item.type) }}</text>
          </view>
          <view class="item-detail" v-if="item.remark">
            <text class="detail-label">地址：</text>
            <text class="detail-value">{{ item.remark }}</text>
          </view>
        </view>
        
        <view class="item-footer">
          <view class="footer-left">
            <text class="payment-time">{{ formatTime(item.payTime || item.createTime) }}</text>
            <text class="payment-channel">{{ getPaymentChannel(item.payChannel) }}</text>
          </view>
          <view class="footer-right">
            <text class="amount">¥{{ (item.totalPrice || 0).toFixed(2) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="loading">
        <text class="load-text">正在加载...</text>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && recordList.length > 0">
        <text class="no-more-text">没有更多数据了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="recordList.length === 0 && !loading">
        <text class="empty-icon">📋</text>
        <text class="empty-text">暂无缴费记录</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getDoorInfoList } from '@/api/door/info'

export default {
  data() {
    return {
      stats: {
        totalAmount: '¥0.00',
        totalCount: 0,
        monthAmount: '¥0.00'
      },
      recordList: [],
      loading: false,
      selectedStatus: '1',  // 默认选择已付款
      dateRange: {
        start: '',
        end: ''
      },
      pageNum: 1,
      pageSize: 10,
      hasMore: true
    }
  },
  computed: {
    dateRangeText() {
      if (this.dateRange.start && this.dateRange.end) {
        return `${this.dateRange.start} 至 ${this.dateRange.end}`
      }
      return '全部时间'
    },
    statusText() {
      const statusMap = {
        '0': '代付款',
        '1': '已付款',
        '2': '退款中',
        '3': '已退款'
      }
      return statusMap[this.selectedStatus] || '全部状态'
    }
  },
  onLoad() {
    this.loadData()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData()
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 导出记录
    exportRecords() {
      this.$modal.loading('正在导出...')
      setTimeout(() => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('导出成功')
      }, 2000)
    },
    
    // 显示日期选择器
    showDatePicker() {
      this.$modal.msgInfo('日期筛选功能开发中')
    },
    
    // 显示状态选择器
    showStatusPicker() {
      uni.showActionSheet({
        itemList: ['已付款', '代付款', '退款中', '已退款', '全部状态'],
        success: (res) => {
          const statusMap = ['1', '0', '2', '3', '']  // 调整顺序，默认显示已付款
          this.selectedStatus = statusMap[res.tapIndex]
          this.pageNum = 1
          this.loadData()
        }
      })
    },
    
    // 加载数据
    async loadData() {
      if (this.loading) return
      
      this.loading = true
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        // 添加状态筛选
        if (this.selectedStatus) {
          params.orderStatus = this.selectedStatus
        }
        
        const response = await getDoorInfoList(params)
        
        if (response.code === 200 && response.rows) {
          const newData = response.rows.map(item => ({
            id: item.id,
            orderNo: item.orderNo,
            chName: item.chName,
            chMobile: item.chMobile,
            totalPrice: item.totalPrice,
            payTime: item.payTime,
            createTime: item.createTime,
            orderStatus: item.orderStatus,
            payChannel: item.payChannel,
            remark: item.remark,
            type: item.type,
            refundCreateTime: item.refundCreateTime,
            refundTime: item.refundTime
          }))
          
          if (this.pageNum === 1) {
            this.recordList = newData
          } else {
            this.recordList.push(...newData)
          }
          
          // 检查是否还有更多数据
          this.hasMore = response.rows.length >= this.pageSize
          
          // 更新统计数据
          this.updateStats()
        } else {
          this.$modal.msgError(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('加载缴费记录失败:', error)
        this.$modal.msgError('网络异常，请稍后重试')
      } finally {
        this.loading = false
        if (this.pageNum === 1) {
          uni.stopPullDownRefresh()
        }
      }
    },
    
    // 更新统计数据
    updateStats() {
      const totalAmount = this.recordList.reduce((sum, item) => sum + (item.totalPrice || 0), 0)
      const currentMonth = new Date().getMonth() + 1
      const currentYear = new Date().getFullYear()
      const monthAmount = this.recordList
        .filter(item => {
          const itemDate = new Date(item.payTime || item.createTime)
          return itemDate.getMonth() + 1 === currentMonth && itemDate.getFullYear() === currentYear
        })
        .reduce((sum, item) => sum + (item.totalPrice || 0), 0)
      
      this.stats.totalAmount = `¥${totalAmount.toFixed(2)}`
      this.stats.totalCount = this.recordList.length
      this.stats.monthAmount = `¥${monthAmount.toFixed(2)}`
    },
    
    // 刷新数据
    refreshData() {
      this.pageNum = 1
      this.loadData()
    },
    
    // 加载更多
    loadMore() {
      this.pageNum++
      this.loadData()
    },
    
    // 查看详情
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/payment/detail?id=${item.id}`
      })
    },
    
    // 下载凭证
    downloadReceipt(item) {
      this.$modal.loading('正在下载...')
      setTimeout(() => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('下载成功')
      }, 1500)
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const classMap = {
        '0': 'status-pending',  // 代付款
        '1': 'status-success',  // 已付款
        '2': 'status-refunding', // 退款中
        '3': 'status-refunded'  // 已退款
      }
      return classMap[status] || 'status-pending'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        '0': '代付款',
        '1': '已付款',
        '2': '退款中',
        '3': '已退款'
      }
      return textMap[status] || '代付款'
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 获取支付类型
    getPaymentType(type) {
      const typeMap = {
        '1': '运维费',
        '3': '买卡',
        '4': '人脸'
      };
      return typeMap[type] || '未知类型';
    },

    // 获取支付渠道
    getPaymentChannel(channel) {
      const channelMap = {
        '1': '微信支付',
        '2': '银行卡',
        '3': '银行卡',
        '4': '现金',
        '5': '其他'
      };
      return channelMap[channel] || '未知渠道';
    }
  }
}
</script>

<style lang="scss" scoped>
.payment-record-container {
  background-color: #f5f6f7;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .nav-export {
    color: #007AFF;
    font-size: 28rpx;
  }
}

.stats-section {
  padding: 20rpx;
}

.stats-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  
  .stats-item {
    text-align: center;
    
    .stats-num {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .stats-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.filter-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #eee;
  
  .filter-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
    }
    
    .filter-value {
      font-size: 26rpx;
      color: #666;
      flex: 1;
      text-align: right;
      margin-right: 20rpx;
    }
    
    .filter-arrow {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.record-list {
  padding: 20rpx;
}

.record-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .item-info {
      display: flex;
      flex-direction: column;
      margin-right: 20rpx;
    }

    .item-name {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }

    .item-phone {
      font-size: 24rpx;
      color: #666;
    }

    .item-status {
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      
      &.status-success {
        background-color: #e8f5e8;
        color: #52c41a;
      }
      
      &.status-pending {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-refunding {
        background-color: #fff2e8;
        color: #fa8c16;
      }
      
      &.status-refunded {
        background-color: #f0f0f0;
        color: #666;
      }
    }
  }
  
  .item-body {
    .item-detail {
      display: flex;
      margin-bottom: 15rpx;
      
      .detail-label {
        font-size: 26rpx;
        color: #666;
        width: 130rpx;
      }
      
      .detail-value {
        font-size: 26rpx;
        color: #333;
        flex: 1;
      }
    }
  }
  
  .item-footer {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .footer-left {
      display: flex;
      flex-direction: column;
      font-size: 24rpx;
      color: #999;
    }

    .payment-time {
      margin-bottom: 5rpx;
    }

    .payment-channel {
      font-size: 24rpx;
    }
    
    .footer-right {
      .amount {
        font-size: 28rpx;
        color: #52c41a;
        font-weight: bold;
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666;
}

.no-more {
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}
</style> 
